package com.leapp.sk.ui.activity.personal

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import cc.vv.lkbasecomponent.http.LKHttp
import cc.vv.lkbasecomponent.http.lib.setting.Settings
import cc.vv.lklibrary.http.base.okhttpfactory.plugins.httpplugin.MediaTypeWrap
import com.example.baselibrary.util.LKToastUtil
import com.example.inter.ItemClickInterface
import com.example.mvp.activity.BaseActivityMVP
import com.example.mvp.binder.BaseDataBinder
import com.example.util.FileSizeUtil
import com.example.util.MD5
import com.example.util.ObjectProcessingUtil
import com.leapp.sk.R
import com.leapp.sk.app.ADD_FEED_BACK
import com.leapp.sk.app.DELETE_FILE
import com.leapp.sk.app.UP_FILE
import com.leapp.sk.bean.UPFileEntity
import com.leapp.sk.bean.request.DeleteFileRequestEntity
import com.leapp.sk.bean.request.login.UPFileRequestEntity
import com.leapp.sk.bean.request.personal.FeedBackSubmitRequestEntity
import com.leapp.sk.bean.response.BaseResponseDataEntity
import com.leapp.sk.bean.response.DeleteFileResponseEntity
import com.leapp.sk.bean.response.login.UPFileResponseEntity
import com.leapp.sk.binder.BaseBinder
import com.leapp.sk.inter.ImagePathInterface
import com.example.util.finallist.SKCODE_200
import com.leapp.sk.util.getResultFile
import com.leapp.sk.viewdelegate.personal.FeedProblemDelegate
import java.io.File
import java.io.IOException

/**
 * 反馈问题
 * @author  chaohaipeng  on 2018/8/9.
 */
class FeedProblemActiviaty : BaseActivityMVP<FeedProblemDelegate>(), ImagePathInterface, ItemClickInterface {

    override fun getArrayImagePath(path: List<String>) {
        for (i in path.indices) {
            val file = File(path.get(i))
            if (file.exists()) {
                httpUpFile(file)
            }
        }
    }

    var imagePath: MutableList<String>? = null
    var fileIds: MutableList<String>? = null
    override fun initDate() {
        imagePath = mutableListOf()
        fileIds = mutableListOf()
        viewDelegate.initImageAdapter(this@FeedProblemActiviaty, imagePath!!, 4,this)
    }

    override fun bindEvenListener() {
        viewDelegate.setOnClickListener(View.OnClickListener {
            viewDelegate.setType(true, false, false, false)
        }, R.id.tv_afp_function)
        viewDelegate.setOnClickListener(View.OnClickListener {
            viewDelegate.setType(false, true, false, false)
        }, R.id.tv_afp_proposal)
        viewDelegate.setOnClickListener(View.OnClickListener {
            viewDelegate.setType(false, false, true, false)
        }, R.id.tv_afp_content)
        viewDelegate.setOnClickListener(View.OnClickListener {
            viewDelegate.setType(false, false, false, true)
        }, R.id.tv_afp_other)

        viewDelegate.setOnClickListener(View.OnClickListener {
            if (TextUtils.isEmpty(viewDelegate.getProblemText())) {
                LKToastUtil.showToastShort(resources.getString(R.string.string_feed_back_hint_content))
                return@OnClickListener
            } else {
                LKToastUtil.showToastShort(resources.getString(R.string.app_submit_success))
            }
            httpFeed()

        }, R.id.tv_afp_submit)

    }

    override fun itemClick(position: Int) {
        if (imagePath != null && fileIds!=null) {
            if (imagePath!!.size==fileIds!!.size&&imagePath!!.size>0){
                val path = imagePath!!.get(position)
                val id = fileIds!!.get(position)
                httpdelete(id,path )
            }
        }

    }

    override fun getDelegateClass(): Class<FeedProblemDelegate> {
        return FeedProblemDelegate::class.java
    }

    override fun getDataBinder(): BaseDataBinder<*, *> {
        return BaseBinder()
    }

    override fun initView(p0: Bundle?) {
        viewDelegate.setTitle(resources.getString(R.string.string_feed_back_question))
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        getResultFile(requestCode, resultCode, data, this, this)
    }

    /**
     * 获取反馈列表
     */
    private fun httpFeed() {
        if (fileIds!=null&&fileIds!!.size>0){
            val stringBuilder = StringBuilder()
            for (i in fileIds!!.indices){
                stringBuilder.append(fileIds!!.get(i)).append(",")
            }
            if (stringBuilder.length>0){
                stringBuilder.delete(stringBuilder.length-1,stringBuilder.length)
            }

        }
        val feedBackSubmitRequestEntity = FeedBackSubmitRequestEntity()
        feedBackSubmitRequestEntity.createUser = feedBackSubmitRequestEntity.userId
        feedBackSubmitRequestEntity.contactMail = viewDelegate.getEmileText()
        feedBackSubmitRequestEntity.backInfo = viewDelegate.getProblemText()
        feedBackSubmitRequestEntity.backType = viewDelegate.getProblemType()

        LKHttp.post(ADD_FEED_BACK, feedBackSubmitRequestEntity, BaseResponseDataEntity::class.java, object : BaseCallBack<BaseResponseDataEntity>(this) {
            override fun onSuccess(url: String?, resultText: String?, obj: BaseResponseDataEntity?) {
                super.onSuccess(url, resultText, obj)
                if (obj?.code == SKCODE_200) {
                  finish()
                } else {
                    LKToastUtil.showToastShort(obj?.message)
                }
            }

            override fun onFailure(url: String?, isLoading: Boolean, exceptionStr: String?) {
                super.onFailure(url, isLoading, exceptionStr)
                LKToastUtil.showToastShort(resources.getString(R.string.app_net_erro))
            }
        }
                , true, Settings(MediaTypeWrap.MEDIA_TYPE_FORM))

    }

    /**
     * 上传文件
     */
    private fun httpUpFile(file: File?) {
        if (file == null) {
            return
        }
        val upFileRequestEntity = UPFileRequestEntity()
        upFileRequestEntity.appKey = "leapp_sk"
        upFileRequestEntity.ext = FileSizeUtil.getInstance().getFileHname(file.absolutePath)
        upFileRequestEntity.file = file
        try {
            upFileRequestEntity.md5 = (MD5.md5(file))
        } catch (e: IOException) {
            e.printStackTrace()
        }
        upFileRequestEntity.fileSize = FileSizeUtil.getInstance().getFileOrFilesIntSize(file.absolutePath, FileSizeUtil.SIZETYPE_KB)
        LKHttp.upLoad(UP_FILE, upFileRequestEntity, UPFileResponseEntity::class.java, object : BaseCallBack<UPFileResponseEntity>(this) {
            override fun onSuccess(url: String?, resultText: String?, obj: UPFileResponseEntity?) {
                super.onSuccess(url, resultText, obj)
                if (obj?.statusCode == SKCODE_200) {
                    val upFileData: UPFileEntity = ObjectProcessingUtil.objMandatoryConversionClass(obj?.data, UPFileEntity::class.java)
                    imagePath?.add(file.absolutePath)
                    fileIds?.add(upFileData?.fileId!!)
                    viewDelegate.notifyAdapter(imagePath!!.size)
                    viewDelegate.horizontal_layout(4)
                } else {
                    LKToastUtil.showToastShort(obj?.statusMessage)
                }
            }

            override fun onFailure(url: String?, isLoading: Boolean, exceptionStr: String?) {
                super.onFailure(url, isLoading, exceptionStr)
                LKToastUtil.showToastShort(resources.getString(R.string.app_net_erro))
            }
        }
                , true, Settings(MediaTypeWrap.MEDIA_TYPE_FORM))

    }

    /**
     * 删除文件
     */
    private fun httpdelete(fileid: String?, path: String?) {
        if (fileid == null) {
            return
        }
        val deleteFileRequestEntity = DeleteFileRequestEntity()
        deleteFileRequestEntity.appKey = "leapp_sk"
        deleteFileRequestEntity.fileId = fileid
        LKHttp.delete(DELETE_FILE, deleteFileRequestEntity, DeleteFileResponseEntity::class.java, object : BaseCallBack<DeleteFileResponseEntity>(this) {
            override fun onSuccess(url: String?, resultText: String?, obj: DeleteFileResponseEntity?) {
                super.onSuccess(url, resultText, obj)
                if (obj?.code == SKCODE_200) {
                    if (fileIds!!.contains(fileid)) {
                        fileIds!!.remove(fileid)
                    }
                    if (imagePath!!.contains(path)) {
                        imagePath!!.remove(path)
                    }
                    viewDelegate.notifyAdapter(imagePath!!.size)
                    viewDelegate.horizontal_layout(4)
                } else {
                    LKToastUtil.showToastShort(obj?.message)
                }
            }

            override fun onFailure(url: String?, isLoading: Boolean, exceptionStr: String?) {
                super.onFailure(url, isLoading, exceptionStr)
                LKToastUtil.showToastShort(resources.getString(R.string.app_net_erro))
            }
        }
                , true, Settings(MediaTypeWrap.MEDIA_TYPE_FORM))

    }
}